import React from "react";
import { RootDispatchContext } from "./context";
import { ACTIONS } from "./constants";
import {
  getUserInfo,
  login as loginApi,
  logout as logoutApi,
} from "../../api/user";
import { getIPSetInfo, getIPSets } from "../../api/ipset";

export function useDispatch() {
  const dispatch = React.useContext(RootDispatchContext);

  if (dispatch === null) {
    throw new Error(
      "'RootDispatchContext' cannot be null, please add 'RootProvider' to the root component."
    );
  }
  const login = React.useCallback(
    async (username: string, password: string): Promise<boolean> => {
      const res = await loginApi(username, password);
      if (res) {
        dispatch({
          type: ACTIONS.SET_USERINFO,
          user: res,
        });
        return true;
      }
      return false;
    },
    [dispatch]
  );

  const logout = React.useCallback(() => {
    logoutApi();
    dispatch({
      type: ACTIONS.LOGOUT,
    });
  }, [dispatch]);

  const refreshUserInfo = React.useCallback(async () => {
    const res = await getUserInfo();
    dispatch({
      type: ACTIONS.SET_USERINFO,
      user: res,
    });
    return !!res;
  }, [dispatch]);

  const refreshIPSets = React.useCallback(async () => {
    const res = await getIPSets();
    dispatch({
      type: ACTIONS.SET_IPSETS,
      ipsets: res,
    });

    return res;
  }, [dispatch]);

  const refreshIPSetInfo = React.useCallback(
    async (setname: string) => {
      const res = await getIPSetInfo(setname);
      dispatch({
        type: ACTIONS.SET_IPSETINFO,
        setname: setname,
        info: res,
      });

      return res;
    },
    [dispatch]
  );

  return {
    login,
    logout,
    refreshUserInfo,
    refreshIPSets,
    refreshIPSetInfo,
  };
}
